package service

import (
	"fmt"
	systemConfig "gin-worked/app/system/config"
	"gin-worked/app/system/extend"
	"gin-worked/app/system/model"
	"gin-worked/dao"
	"github.com/mitchellh/mapstructure"
	"strconv"
	"time"
)

func DataSheetList(id string) Res {

	data := &model.DataSheet{}
	i := 0

	data.DelTime = &i
	data.Status = 1
	if id != "" {
		ids, _ := strconv.Atoi(id)
		data.ParentId = &ids
	} else {

		data.ParentId = &i
	}

	field := []string{"id", "title", "type", "length", "remark", "default_value", "parent_id", "status", "is_validation", "create_time"} //查询字段
	list, err := model.DataSheetListAll(data, field, "id ASC")

	if err != nil {
		return Res{0, err.Error(), ""}
	}

	return Res{1, "success", list}
}

// DataSheetAdd 添加数据表(或者数据表下的字段)
func DataSheetAdd(title string, types string, length string, remark string, defaultValue string, parentId string, status string, isValidation string) Res {
	statusEs, _ := strconv.Atoi(status)
	lengthEs, _ := strconv.Atoi(length)
	parentIds, _ := strconv.Atoi(parentId)
	isValidationEs, _ := strconv.Atoi(isValidation)

	where := &model.DataSheet{}

	where.Title = title
	i := 0
	if parentIds > 0 {
		where.ParentId = &parentIds
	} else {

		where.ParentId = &i
	}

	field := []string{"id"} //查询字段
	info, _ := model.DataSheetInfo(where, field)

	//fmt.Println(err1.Error())
	//验证标题是否在同一张表是否存在或者表名是否存在
	if info.Id > 0 {
		return Res{0, "该标题已存在", ""}
	}

	times := time.Now().Unix()
	data := &model.DataSheet{
		Title:        title,
		Type:         types,
		Length:       lengthEs,
		Remark:       remark,
		DefaultValue: defaultValue,
		ParentId:     &parentIds,
		Status:       statusEs,
		IsValidation: isValidationEs,
		CreateTime:   int(times),
		UpdateTime:   int(times),
		DelTime:      &i,
	}

	id, err := model.DataSheetAdd(data)
	if err != nil {
		return Res{0, err.Error(), ""}
	}

	return Res{1, "success", id}
}

// DataSheetInfo 获取详情
func DataSheetInfo(id string) Res {
	ids, _ := strconv.Atoi(id)

	where := &model.DataSheet{
		Id: ids,
	}
	field := []string{"id", "title", "type", "length", "remark", "default_value", "parent_id", "status", "is_validation", "create_time"} //查询字段
	info, err := model.DataSheetInfo(where, field)
	if err != nil {
		return Res{0, err.Error(), ""}
	}
	return Res{1, "success", info}
}

func DataSheetEdit(id string, title string, types string, length string, remark string, defaultValue string, parentId string, status string, isValidation string) Res {
	statusEs, _ := strconv.Atoi(status)
	lengthEs, _ := strconv.Atoi(length)
	parentIds, _ := strconv.Atoi(parentId)
	isValidationEs, _ := strconv.Atoi(isValidation)
	ids, _ := strconv.Atoi(id)

	var content = map[string]interface{}{"title": title, "type": types, "length": lengthEs, "remark": remark, "default_value": defaultValue, "parent_id": parentIds, "status": statusEs, "is_validation": isValidationEs}
	data := &model.DataSheet{Id: ids}

	err := model.DataSheetEdit(data, content)

	if err != nil {
		return Res{0, err.Error(), ""}
	}
	return Res{1, "success", ""}
}

// DataSheetDel 删除
func DataSheetDel(id string) Res {
	ids, _ := strconv.Atoi(id)

	where := &model.DataSheet{
		Id: ids,
	}

	times := time.Now().Unix()

	var content = map[string]interface{}{"del_time": times}
	err := model.DataSheetEdit(where, content)
	if err != nil {
		return Res{0, err.Error(), ""}
	}
	return Res{1, "success", ""}
}

// SelectSql 查询数据库是否存储了 对应的表 没有就自动创建
func SelectSql() Res {

	tableName := model.SelectSql() //获取数据库所有表名称

	data := &model.DataSheet{}
	i := 0
	data.DelTime = &i
	data.Status = 1
	data.ParentId = &i
	field := []string{"title"} //查询字段

	list, _ := model.DataSheetListAll(data, field, "id ASC")

	//提取数据表名称进行下一步操作
	names := make([]string, len(list))
	for i, item := range list {
		names[i] = item.Title
	}

	//将没有在数据库中data_sheet表中的数据表 添加进数据库信息
	var tableNameEs []string
	for _, value := range tableName {
		if systemConfig.Contains(names, value) == false {
			tableNameEs = append(tableNameEs, value)
		}
	}

	tx := dao.Db.Begin()

	times := time.Now().Unix()
	for _, value := range tableNameEs {
		DataSheet := model.DataSheet{}
		//tx.Exec("INSERT INTO tp_data_sheet (title, status,create_time,update_time,is_validation) VALUES (?, ?,?,?,?)", value, 1, times, times, 0) //添加数据库

		DataSheet.Title = value
		DataSheet.Status = 1
		DataSheet.CreateTime = int(times)
		DataSheet.UpdateTime = int(times)
		DataSheet.IsValidation = 0
		DataSheet.Length = 0
		DataSheet.ParentId = &i
		DataSheet.DefaultValue = ""
		DataSheet.Remark = ""
		tableId, err := model.WorkAdd(tx, &DataSheet)

		if err != nil {
			tx.Rollback()
			return Res{0, err.Error(), ""}
		}

		fieldEd := model.SelectSqlField(value) //获取以创建数据库字段

		for _, item := range fieldEd {
			DataSheets := model.DataSheet{}
			// 获取type类型的值
			DataTypeValue := item["DataTypeValue"].(interface{})
			var result map[string]interface{}
			if err := mapstructure.Decode(DataTypeValue, &result); err != nil {
				tx.Rollback()
				return Res{0, err.Error(), ""}
			}

			DataSheets.Type = result["String"].(string)

			//备注 remark
			CommentValue := item["CommentValue"].(interface{})
			var CommentValueED map[string]interface{}
			if err2 := mapstructure.Decode(CommentValue, &CommentValueED); err != nil {
				tx.Rollback()
				return Res{0, err2.Error(), ""}
			}
			DataSheets.Remark = CommentValueED["String"].(string)

			//长度 length
			DecimalSizeValue := item["DecimalSizeValue"].(interface{})

			var DecimalSizeValueED map[string]interface{}
			if err := mapstructure.Decode(DecimalSizeValue, &DecimalSizeValueED); err != nil {
				tx.Rollback()
				return Res{0, err.Error(), ""}
			}
			//return Res{Msg: "success", Data: DecimalSizeValueED["Int64"].(int64)}
			DataSheets.Length = int(DecimalSizeValueED["Int64"].(int64))

			//标题 title
			NameValue := item["NameValue"].(interface{})
			var NameValueED map[string]interface{}
			if err := mapstructure.Decode(NameValue, &NameValueED); err != nil {
				tx.Rollback()
				return Res{0, err.Error(), ""}
			}
			DataSheets.Title = NameValueED["String"].(string)
			//默认值 default_value
			DefaultValueValue := item["DefaultValueValue"].(interface{})
			var DefaultValueValueEd map[string]interface{}
			if err := mapstructure.Decode(DefaultValueValue, &DefaultValueValueEd); err != nil {
				tx.Rollback()
				return Res{0, err.Error(), ""}
			}
			DataSheets.DefaultValue = DefaultValueValueEd["String"].(string)

			DataSheets.ParentId = &tableId
			DataSheets.IsValidation = 0
			DataSheets.UpdateTime = int(times)
			DataSheets.CreateTime = int(times)
			DataSheets.Status = 1
			DataSheets.DelTime = &i

			_, err1 := model.WorkAdd(tx, &DataSheets)

			if err1 != nil {
				tx.Rollback()
				return Res{0, err1.Error(), ""}
			}

		}
	}
	tx.Commit()
	//
	return Res{1, "success", ""}
}

// CreateSql 创建数据表
func CreateSql(id string) Res {

	ids, _ := strconv.Atoi(id)
	data := &model.DataSheet{
		Id: ids,
	}
	field := []string{"id", "title", "type", "length", "remark", "parent_id"} //查询字段
	info, err := model.DataSheetInfo(data, field)                             //获取要创建的表

	if err != nil {
		return Res{0, err.Error(), ""}
	}
	var parentId int
	parentId = *info.ParentId
	if parentId > 0 {
		return Res{0, "该数据不是表", ""}
	}
	var i = 0
	where := &model.DataSheet{
		ParentId: &ids,
		Status:   1,
		DelTime:  &i,
	}

	fields := []string{"id", "title", "type", "length", "remark", "default_value", "is_validation", "parent_id"} //查询字段
	list, _ := model.DataSheetListAll(where, fields, "create_time ASC")                                          //获取要创建的字段

	// 创建数据表的SQL语句

	var str string
	var only = 0
	for _, value := range list {
		var defaultValue = " DEFAULT NULL"
		if value.DefaultValue != "" {
			defaultValue = " unsigned DEFAULT '" + value.DefaultValue + "'"
		}
		if value.Title == "id" {
			defaultValue = " unsigned NOT NULL AUTO_INCREMENT"
			only = 1
		}
		var remark string
		if value.Remark != "" {
			remark = " COMMENT '" + value.Remark + "'"
		}

		str += value.Title + " " + value.Type + "(" + strconv.Itoa(value.Length) + ")" + defaultValue + remark + ","
	}

	if only == 1 {
		str += " PRIMARY KEY (id)"
	}
	var tableRearmk string
	if info.Remark != "" {
		tableRearmk = "COMMENT='" + info.Remark + "';"
	}

	sql := fmt.Sprintf("CREATE TABLE IF NOT EXISTS %s  ("+str+")"+tableRearmk, info.Title)
	warn := dao.Db.Exec(sql).Error

	if warn != nil {
		return Res{0, warn.Error(), ""}
	}
	return Res{1, "success", ""}

}

// CreateFile 创建对应的业务文件
func CreateFile(id string) Res {
	ids, _ := strconv.Atoi(id)
	data := &model.DataSheet{
		Id: ids,
	}
	field := []string{"id", "title", "type", "length", "remark", "parent_id"} //查询字段
	info, err := model.DataSheetInfo(data, field)                             //获取要创建的表

	if err != nil {
		return Res{0, err.Error(), ""}
	}
	var parentId int
	parentId = *info.ParentId
	if parentId > 0 {
		return Res{0, "该数据不是表", ""}
	}
	var i = 0
	where := &model.DataSheet{
		ParentId: &ids,
		Status:   1,
		DelTime:  &i,
	}

	fields := []string{"id", "title", "type", "length", "remark", "default_value", "is_validation", "parent_id"} //查询字段
	list, _ := model.DataSheetListAll(where, fields, "create_time ASC")                                          //获取要创建的字段
	e := extend.CreateFile(info, list)

	if err != nil {
		return Res{0, e.Error(), ""}
	}

	return Res{1, "success", ""}
}
